<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import { WalletOutlined, DisconnectOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { blockchainService } from '../../services/blockchain'

// 响应式状态
const isConnected = ref(false)
const isConnecting = ref(false)
const currentAccount = ref<string | null>(null)
const accountBalance = ref<string>('0')
const networkId = ref<string>('')
const isCorrectNetwork = ref(true)

// 计算属性
const shortAddress = computed(() => {
  if (!currentAccount.value) return ''
  return `${currentAccount.value.slice(0, 6)}...${currentAccount.value.slice(-4)}`
})

const networkStatus = computed(() => {
  return isCorrectNetwork.value ? '✅ 正确网络' : '❌ 网络错误'
})

const networkStatusColor = computed(() => {
  return isCorrectNetwork.value ? 'success' : 'error'
})

// 初始化
onMounted(async () => {
  await initWallet()
})

/**
 * 初始化钱包
 */
async function initWallet() {
  try {
    console.log('🔄 初始化钱包...')
    
    // 初始化 Web3
    await blockchainService.init()
    
    // 检查是否已连接
    const account = await blockchainService.getCurrentAccount()
    if (account) {
      currentAccount.value = account
      isConnected.value = true
      await loadAccountInfo()
    }
    
    // 检查网络
    await checkNetwork()
    
    console.log('✅ 钱包初始化完成')
  } catch (error) {
    console.error('❌ 钱包初始化失败:', error)
  }
}

/**
 * 连接钱包
 */
async function connectWallet() {
  if (isConnecting.value) return
  
  isConnecting.value = true
  
  try {
    console.log('🔗 连接钱包...')
    
    // 连接 MetaMask
    const account = await blockchainService.connectWallet()
    currentAccount.value = account
    isConnected.value = true
    
    // 加载账户信息
    await loadAccountInfo()
    
    // 检查网络
    await checkNetwork()
    
    message.success(`钱包连接成功！账户: ${shortAddress.value}`)
    console.log('✅ 钱包连接成功:', account)
    
  } catch (error: any) {
    console.error('❌ 钱包连接失败:', error)
    
    if (error.code === 4001) {
      message.error('用户拒绝了连接请求')
    } else if (error.code === -32002) {
      message.error('连接请求已存在，请检查 MetaMask')
    } else {
      message.error(`连接失败: ${error.message || '未知错误'}`)
    }
  } finally {
    isConnecting.value = false
  }
}

/**
 * 断开钱包连接
 */
function disconnectWallet() {
  currentAccount.value = null
  accountBalance.value = '0'
  isConnected.value = false
  networkId.value = ''
  isCorrectNetwork.value = true
  
  message.info('钱包已断开连接')
  console.log('🔌 钱包已断开连接')
}

/**
 * 加载账户信息
 */
async function loadAccountInfo() {
  if (!currentAccount.value) return
  
  try {
    console.log('📊 加载账户信息...')
    
    // 获取余额
    const balance = await blockchainService.getBalance(currentAccount.value)
    accountBalance.value = parseFloat(balance).toFixed(4)
    
    // 获取网络信息
    await checkNetwork()
    
    console.log('✅ 账户信息加载完成')
  } catch (error) {
    console.error('❌ 加载账户信息失败:', error)
  }
}

/**
 * 检查网络
 */
async function checkNetwork() {
  try {
    const web3 = blockchainService.getWeb3()
    const currentNetworkId = await web3.eth.net.getId()
    const expectedNetworkId = import.meta.env.VITE_NETWORK_ID || '20241214'
    
    // 将 BigInt 或 Number 转换为字符串
    const currentNetworkIdStr = String(currentNetworkId)
    networkId.value = currentNetworkIdStr
    isCorrectNetwork.value = currentNetworkIdStr === expectedNetworkId
    
    if (!isCorrectNetwork.value) {
      console.warn(`⚠️ 网络 ID 不匹配，期望 ${expectedNetworkId}，实际 ${currentNetworkIdStr}`)
    }
    
    console.log('🌐 网络检查完成:', { networkId: currentNetworkIdStr, expectedNetworkId })
  } catch (error) {
    console.error('❌ 网络检查失败:', error)
    isCorrectNetwork.value = false
  }
}

/**
 * 切换网络
 */
async function switchNetwork() {
  if (!isCorrectNetwork.value && (window as any).ethereum) {
    try {
      const expectedNetworkId = import.meta.env.VITE_NETWORK_ID || '20241214'
      const rpcUrl = import.meta.env.VITE_WEB3_RPC_URL || 'http://localhost:8545'
      
      await (window as any).ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: `0x${parseInt(expectedNetworkId).toString(16)}` }],
      })
      
      await checkNetwork()
      message.success('网络切换成功')
    } catch (error: any) {
      if (error.code === 4902) {
        // 网络不存在，添加网络
        try {
          await (window as any).ethereum.request({
            method: 'wallet_addEthereumChain',
            params: [{
              chainId: `0x${parseInt(import.meta.env.VITE_NETWORK_ID || '20241214').toString(16)}`,
              chainName: 'FamilyChain',
              rpcUrls: [import.meta.env.VITE_WEB3_RPC_URL || 'http://localhost:8545'],
              nativeCurrency: {
                name: 'ETH',
                symbol: 'ETH',
                decimals: 18,
              },
            }],
          })
          
          await checkNetwork()
          message.success('网络添加成功')
        } catch (addError) {
          console.error('❌ 添加网络失败:', addError)
          message.error('添加网络失败，请手动添加')
        }
      } else {
        console.error('❌ 切换网络失败:', error)
        message.error('切换网络失败')
      }
    }
  }
}

/**
 * 刷新账户信息
 */
async function refreshAccount() {
  if (isConnected.value) {
    await loadAccountInfo()
    message.success('账户信息已刷新')
  }
}
</script>

<template>
  <div class="wallet-connect">
    <!-- 未连接状态 -->
    <div v-if="!isConnected" class="wallet-disconnected">
      <a-button 
        type="primary" 
        size="large"
        :loading="isConnecting"
        @click="connectWallet"
        class="connect-button"
      >
        <template #icon>
          <WalletOutlined />
        </template>
        {{ isConnecting ? '连接中...' : '连接钱包' }}
      </a-button>
      
      <div class="wallet-tips">
        <p>🔗 连接 MetaMask 钱包开始使用</p>
        <p>📱 请确保已安装 MetaMask 浏览器插件</p>
      </div>
    </div>

    <!-- 已连接状态 -->
    <div v-else class="wallet-connected">
      <!-- 账户信息卡片 -->
      <a-card size="small" class="account-card">
        <template #title>
          <div class="account-header">
            <WalletOutlined style="color: #52c41a; margin-right: 8px;" />
            <span>钱包已连接</span>
          </div>
        </template>
        
        <div class="account-info">
          <!-- 账户地址 -->
          <div class="account-address">
            <span class="label">账户地址:</span>
            <a-tag color="blue" class="address-tag">
              {{ shortAddress }}
            </a-tag>
            <a-button 
              type="text" 
              size="small" 
              @click="refreshAccount"
              title="刷新账户信息"
            >
              <ReloadOutlined />
            </a-button>
          </div>
          
          <!-- 账户余额 -->
          <div class="account-balance">
            <span class="label">余额:</span>
            <span class="balance">{{ accountBalance }} ETH</span>
          </div>
          
          <!-- 网络状态 -->
          <div class="network-status">
            <span class="label">网络:</span>
            <a-tag :color="networkStatusColor" class="network-tag">
              {{ networkStatus }}
            </a-tag>
            <span class="network-id">(ID: {{ networkId }})</span>
            
            <!-- 网络切换按钮 -->
            <a-button 
              v-if="!isCorrectNetwork"
              type="link" 
              size="small" 
              @click="switchNetwork"
              class="switch-network-btn"
            >
              切换到正确网络
            </a-button>
          </div>
        </div>
        
        <template #extra>
          <a-button 
            type="text" 
            danger 
            size="small"
            @click="disconnectWallet"
            title="断开连接"
          >
            <DisconnectOutlined />
          </a-button>
        </template>
      </a-card>
      
      <!-- 连接状态指示器 -->
      <div class="connection-indicator">
        <a-badge status="success" text="钱包已连接" />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.wallet-connect {
  .wallet-disconnected {
    text-align: center;
    padding: 24px;
    
    .connect-button {
      height: 48px;
      padding: 0 32px;
      font-size: 16px;
      border-radius: 8px;
      box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(24, 144, 255, 0.4);
      }
    }
    
    .wallet-tips {
      margin-top: 16px;
      color: #666;
      font-size: 14px;
      
      p {
        margin: 4px 0;
      }
    }
  }
  
  .wallet-connected {
    .account-card {
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      
      :deep(.ant-card-head) {
        border-bottom: 1px solid #f0f0f0;
        
        .ant-card-head-title {
          padding: 12px 0;
          font-weight: 600;
        }
      }
      
      .account-header {
        display: flex;
        align-items: center;
        font-size: 16px;
      }
      
      .account-info {
        .account-address,
        .account-balance,
        .network-status {
          display: flex;
          align-items: center;
          margin-bottom: 12px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .label {
            min-width: 80px;
            font-weight: 500;
            color: #666;
          }
          
          .balance {
            font-weight: 600;
            color: #1890ff;
          }
          
          .network-id {
            margin-left: 8px;
            font-size: 12px;
            color: #999;
          }
          
          .switch-network-btn {
            margin-left: 8px;
            padding: 0;
            height: auto;
            font-size: 12px;
          }
        }
        
        .address-tag {
          font-family: 'Courier New', monospace;
          font-size: 12px;
        }
        
        .network-tag {
          font-size: 12px;
        }
      }
    }
    
    .connection-indicator {
      margin-top: 8px;
      text-align: center;
      
      :deep(.ant-badge-status-text) {
        font-size: 12px;
        color: #52c41a;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .wallet-connect {
    .wallet-connected {
      .account-card {
        .account-info {
          .account-address,
          .account-balance,
          .network-status {
            flex-direction: column;
            align-items: flex-start;
            gap: 4px;
            
            .label {
              min-width: auto;
            }
          }
        }
      }
    }
  }
}
</style>
